#!/usr/bin/evn python
# coding=utf-8

import re

import base64

# def password(codekey, salt="xiaozhong", com=8, off=3):
#     "使用base64编码与解码产生密码 encode:编码  decode:解码"
#     new = base64.b64encode((user_password + salt).encode("utf-8"))
#     new = new.decode("utf-8")
#     if len(new) < com:
#         new = new.ljust(com, "a")
#     return new[off : com + off]
import pinyin


def getStrAllAplha(str):
    return pinyin.get_initial(str, delimiter="").upper()


def convert_list_to_str(input_list: list) -> str:
    """Convert list of string to one string"""
    return " ".join(input_list)


def convert_dict_to_str(input_dict: dict) -> str:
    """Converting dict values to one string"""
    return "\n".join(input_dict.values())


def getStrFirstAplha(str):
    str = getStrAllAplha(str)
    str = str[0:1]
    return str.upper()


# str = '你好在哪来'
#
# print(getStrAllAplha(str))
# print(getStrFirstAplha(str))

def check_string(text, pattern):
    """检查字符串"""
    match = re.search(pattern, text)
    if match:
        return True
    else:
        return False


def is_email(text):
    """验证字符串是否是email"""
    return check_string(text, '[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$')


def is_ip(text):
    """验证字符串是否是ip地址"""
    return check_string(text,
                        "^(1\\d{2}|2[0-4]\\d|25[0-5]|[0-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$")


def is_phone(text):
    """验证字符串是否是固定电话"""
    return check_string(text, '\(?0\d{2,3}[) -]?\d{7,8}$')


def is_letters(text):
    """验证字符串是否全是字母"""
    return check_string(text, '^[a-zA-Z]+$')


def is_mobile(text):
    """验证字符串是否是手机号码"""
    return check_string(text, '^1[3578]\d{9}$|^147\d{8}$')


def is_idcard(text):
    """验证字符串是否是身份证号码"""
    ic = IdentityCard()
    return ic.check(text.upper())


def filter_str(text):
    """过滤特殊字符"""
    if text:
        return re.subn('<|>|&|%|\||~|^|;|\'', '', text)[0]
    else:
        return ''


def string(text, is_return_null=False):
    """在字符串两边添加'单撇号，用于生成数据库添加与编辑语句"""
    if not text is None and text != '':
        return "'" + str(text) + "'"
    elif not is_return_null:
        return "''"
    else:
        return "null"


def cut_str(text, length):
    """将字符串截取指定长度"""
    tem = ''
    try:
        tem = text.decode('utf8')[0:length]
    except:
        pass
    if not tem or tem == '':
        try:
            tem = text[0:length]
        except:
            tem = text

    return tem


def format_price(price):
    """将价格格式化为两位小数，不足的加0"""
    if not price:
        return '0.00'

    tem = str(price)
    tem = tem.split('.')
    if len(tem) == 1:
        return tem + '.00'
    if len(tem[1]) == 0:
        return tem + '.00'
    if len(tem[1]) == 1:
        return tem[0] + '.' + tem[1] + '0'
    else:
        return tem[0] + '.' + tem[1][0:2]


class IdentityCard:
    """身份证号码验证类"""

    def __init__(self):
        self.__Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        self.__Ti = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

    def calculate(self, code):
        """计算校验位"""
        sum = 0
        for i in range(17):
            sum += int(code[i]) * self.__Wi[i]
        return self.__Ti[sum % 11]

    def check(self, code):
        """检查输入的号码是否正确"""

        if (len(code) != 18):
            return False
        if self.calculate(code) != code[17]:
            return False

        return True


def get_lower_case_name(text):
    """
        将驼峰模式,转换为下划线分隔的名字
        :param src: test_date
        :return:testDate
        """
    lst = []
    for index, char in enumerate(text):
        if char.isupper() and index != 0:
            lst.append("_")
        lst.append(char)

    return "".join(lst).lower()


def formatter(src: str, firstUpper: bool = True):
    """
    将下划线分隔的名字,转换为驼峰模式
    :param src: test_date
    :param firstUpper: 转换后的首字母是否指定大写(  testDate or  TestDate)
    :return:testDate
    """
    arr = src.split('_')
    res = ''
    for i in arr:
        res = res + i[0].upper() + i[1:]

    if not firstUpper:
        res = res[0].lower() + res[1:]
    return res


# 下划线转驼峰
def str2Hump(text):
    arr = filter(None, text.lower().split('_'))
    res = ''
    j = 0
    for i in arr:
        if j == 0:
            res = i
        else:
            res = res + i[0].upper() + i[1:]
        j += 1
    return res


# 驼峰转下划线
def hump2Underline(text):
    res = []
    for index, char in enumerate(text):
        if char.isupper() and index != 0:
            res.append("_")
        res.append(char)
    return ''.join(res).lower()


# 下划线转驼峰
def underline2Hump(text):
    arr = text.lower().split('_')
    res = []
    if len(arr) > 1:
        for i in arr:
            res.append(i[0].upper() + i[1:])
        return ''.join(res)
    return text


# 下划线转驼峰
def underline2HumpAndFirstLower(text):
    arr = text.lower().split('_')
    res = []
    if len(arr) > 1:
        for i in arr:
            res.append(i[0].upper() + i[1:])
        ererws = ''.join(res)
        return ererws[0].lower() + ererws[1:]
    return text


# 下划线转驼峰
def underline2HumpAndDelis(text):
    arr = text.lower().split('_')
    print('arrarrarr', arr)
    if 'is_' in text and isinstance(arr, list) and len(arr) > 1 and 'is' == arr[0]:
        arr.pop(0)
        if len(arr) == 1:
            text = arr[0]
    res = []
    if len(arr) > 1:
        for i in arr:
            res.append(i[0].upper() + i[1:])
        ererws = ''.join(res)
        return ererws[0].lower() + ererws[1:]
    return text


# 下划线转驼峰
def underline2HumpAndDelis_repace_key(text, keyword='', repace_key=''):
    arr = text.lower().split('_')

    if 'is_' in text and isinstance(arr, list) and len(arr) > 1 and 'is' == arr[0]:
        arr.pop(0)
        if len(arr) == 1:
            text = arr[0]
    res = []
    if len(arr) > 1:
        for i in arr:
            res.append(i[0].upper() + i[1:])
        ererws = ''.join(res)
        result = ererws[0].lower() + ererws[1:]
    else:
        result = text

    if repace_key and keyword and keyword == result:
        return repace_key
    return result


# 下划线转驼峰
def underline2HumpAndDelis_repace_key_map(text, repace_key_map=None):
    if repace_key_map:
        for itemmap in repace_key_map:
            if text in itemmap.keys():
                # 把需要替换的值替换
                text = itemmap[text]

    arr = text.lower().split('_')

    if 'is_' in text and isinstance(arr, list) and len(arr) > 1 and 'is' == arr[0]:
        arr.pop(0)
        if len(arr) == 1:
            text = arr[0]
    res = []
    if len(arr) > 1:
        for i in arr:
            res.append(i[0].upper() + i[1:])
        ererws = ''.join(res)
        result = ererws[0].lower() + ererws[1:]
    else:
        result = text

    # if repace_key and  keyword and keyword == result:
    #     return repace_key
    return result
